package il.technion.cs236369.webserver.typeHandlers;

import il.technion.cs236369.interfaces.ICookie;
import il.technion.cs236369.interfaces.ISession;
import il.technion.cs236369.interfaces.ITypeHandler;
import il.technion.cs236369.webserver.Request;

import java.util.Properties;

import org.apache.http.Header;

/**
 * Generic TypeHandler that accepts the properties, and handles all the cookie
 * management
 * 
 * @author Gal Lalouche
 * 
 */
abstract class TypeHandlerImpl implements ITypeHandler {
	protected final Properties				props;
	protected final static CookieManager	cm	= new CookieManager();

	/**
	 * Creates a new type handler
	 * 
	 * @param props The properties for the handler
	 */
	protected TypeHandlerImpl(Properties props) {
		if (props == null) {
			throw new IllegalArgumentException("props is null");
		}

		this.props = props;
	}

	/**
	 * Gets the cookie associated with the request
	 * 
	 * @param request The request
	 * @return A cookie associated with the request, or null if none is
	 */
	private static ICookie getCookieFromRequest(Request request) {
		Header cookieHeader = request.getRequest().getFirstHeader("Cookie");
		if (cookieHeader != null) {
			return new CookieImpl(Long.parseLong(cookieHeader.getValue().split("=")[1]));
		} else {
			return null;
		}
	}

	/**
	 * Gets the session associated with the request
	 * 
	 * @param request The request
	 * @return The session associated with the request, or null if none are
	 * @throws IllegalArgumentException If the cookie has not been issued by the
	 *             manager
	 */
	protected static ISession getSession(Request request) {
		ICookie cookie = getCookieFromRequest(request);
		ISession session;
		if (cookie == null) {
			session = null;
		} else {
			session = cm.getSession(cookie);
			if (session == null) {
				throw new IllegalArgumentException("bad cookie");
			}
		}
		return session;
	}
}
